package com.misty.blog.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.misty.blog.bean.param.blog.LikeCountParam;
import com.misty.blog.service.BlogLikesService;
import com.misty.common.bean.Result;
import com.misty.common.constants.ResultEnum;
import com.misty.dao.domain.BlogLikes;
import com.misty.dao.mapper.BlogLikesMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 博客点赞表 服务实现类
 * </p>
 *
 * @author cthulhu
 * @since 2022-12-02
 */
@Service
public class BlogLikesServiceImpl extends ServiceImpl<BlogLikesMapper, BlogLikes> implements BlogLikesService {

    @Resource
    private BlogLikesMapper blogLikesMapper;

//    LoginUser principal = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//    Integer currentUserId = principal.getUser().getId();

    /**
     *
     * @Param
     * @return
     * @Description 判断是否点赞过
     * @Date
     **/
    @Override
    public Boolean judgeIfLike(Integer blogId, Integer currentUserId) {

        QueryWrapper<BlogLikes> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BlogLikes::getBlogId,blogId)
                .eq(BlogLikes::getUserId,currentUserId);
        BlogLikes blogLikes = blogLikesMapper.selectOne(queryWrapper);
        if(ObjectUtil.isEmpty(blogLikes)){
            return false;
        }
        return true;
    }

    /**
     *
     * @Param
     * @return
     * @Description 删除对应点赞记录
     * @Date
     **/
    @Override
    public Result<?> cancelLike(LikeCountParam param, Integer currentUserId) {

        //删除对应点赞记录
        UpdateWrapper<BlogLikes> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(BlogLikes::getBlogId,param.getBlogId())
                .eq(BlogLikes::getUserId,currentUserId);
        int remove = blogLikesMapper.delete(updateWrapper);
        if(remove <= 0){
            return Result.error("删除对应点赞记录失败！");
        }
        return Result.success("删除对应点赞记录成功！");
    }

    /**
     *
     * @Param
     * @return
     * @Description 添加点赞
     * @Date
     **/
    @Override
    public Result<?> addLike(LikeCountParam param, Integer currentUserId) {

        //增加对应点赞记录
        BlogLikes insert = new BlogLikes();
        insert.setBlogId(param.getBlogId())
                .setUserId(currentUserId);
        int save = blogLikesMapper.insert(insert);
        if(save <= 0){
            return Result.error("添加点赞失败！");
        }
        return Result.success("添加点赞成功！");
    }

}
